// 快捷键设置面板
// 快捷键配置、冲突检测等功能

import React, { useState, useEffect } from 'react';
import { Search, AlertTriangle, RotateCcw, Edit2, Check, X } from 'lucide-react';
import { useSettingsStore } from '../../../stores/settingsStore';
import { ShortcutConflictDetector } from '../components/ShortcutConflictDetector';

interface ShortcutItem {
  id: string;
  name: string;
  description: string;
  category: string;
  defaultShortcut: string;
  currentShortcut: string;
  conflicts?: string[];
}

// 模拟快捷键数据
const mockShortcuts: ShortcutItem[] = [
  {
    id: 'editor.save',
    name: '保存文件',
    description: '保存当前编辑的文件',
    category: '文件操作',
    defaultShortcut: 'Ctrl+S',
    currentShortcut: 'Ctrl+S'
  },
  {
    id: 'editor.saveAll',
    name: '保存所有文件',
    description: '保存所有打开的文件',
    category: '文件操作',
    defaultShortcut: 'Ctrl+Shift+S',
    currentShortcut: 'Ctrl+Shift+S'
  },
  {
    id: 'tab.close',
    name: '关闭标签页',
    description: '关闭当前标签页',
    category: '标签页操作',
    defaultShortcut: 'Ctrl+W',
    currentShortcut: 'Ctrl+W'
  },
  {
    id: 'tab.next',
    name: '下一个标签页',
    description: '切换到下一个标签页',
    category: '标签页操作',
    defaultShortcut: 'Ctrl+Tab',
    currentShortcut: 'Ctrl+Tab'
  },
  {
    id: 'edit.undo',
    name: '撤销',
    description: '撤销上一个操作',
    category: '编辑操作',
    defaultShortcut: 'Ctrl+Z',
    currentShortcut: 'Ctrl+Z'
  },
  {
    id: 'search.find',
    name: '查找',
    description: '在当前文件中查找',
    category: '搜索操作',
    defaultShortcut: 'Ctrl+F',
    currentShortcut: 'Ctrl+F'
  }
];

export const KeyboardSettingsPanel: React.FC = () => {
  const [shortcuts, setShortcuts] = useState<ShortcutItem[]>(mockShortcuts);
  const [searchQuery, setSearchQuery] = useState('');
  const [editingShortcut, setEditingShortcut] = useState<string | null>(null);
  const [newShortcut, setNewShortcut] = useState('');
  const [isRecording, setIsRecording] = useState(false);
  const [conflicts, setConflicts] = useState<Record<string, string[]>>({});

  // 过滤快捷键
  const filteredShortcuts = shortcuts.filter(shortcut =>
    shortcut.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    shortcut.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    shortcut.category.toLowerCase().includes(searchQuery.toLowerCase()) ||
    shortcut.currentShortcut.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // 按分类分组
  const groupedShortcuts = filteredShortcuts.reduce((groups, shortcut) => {
    const category = shortcut.category;
    if (!groups[category]) {
      groups[category] = [];
    }
    groups[category].push(shortcut);
    return groups;
  }, {} as Record<string, ShortcutItem[]>);

  // 检测快捷键冲突
  const detectConflicts = (shortcuts: ShortcutItem[]) => {
    const shortcutMap: Record<string, string[]> = {};
    const conflicts: Record<string, string[]> = {};

    shortcuts.forEach(shortcut => {
      const key = shortcut.currentShortcut;
      if (!shortcutMap[key]) {
        shortcutMap[key] = [];
      }
      shortcutMap[key].push(shortcut.id);
    });

    Object.entries(shortcutMap).forEach(([key, ids]) => {
      if (ids.length > 1) {
        ids.forEach(id => {
          conflicts[id] = ids.filter(otherId => otherId !== id);
        });
      }
    });

    setConflicts(conflicts);
  };

  useEffect(() => {
    detectConflicts(shortcuts);
  }, [shortcuts]);

  // 开始编辑快捷键
  const startEditing = (shortcutId: string) => {
    const shortcut = shortcuts.find(s => s.id === shortcutId);
    if (shortcut) {
      setEditingShortcut(shortcutId);
      setNewShortcut(shortcut.currentShortcut);
      setIsRecording(false);
    }
  };

  // 取消编辑
  const cancelEditing = () => {
    setEditingShortcut(null);
    setNewShortcut('');
    setIsRecording(false);
  };

  // 保存快捷键
  const saveShortcut = () => {
    if (editingShortcut && newShortcut) {
      setShortcuts(prev => prev.map(shortcut =>
        shortcut.id === editingShortcut
          ? { ...shortcut, currentShortcut: newShortcut }
          : shortcut
      ));
      cancelEditing();
    }
  };

  // 重置快捷键
  const resetShortcut = (shortcutId: string) => {
    setShortcuts(prev => prev.map(shortcut =>
      shortcut.id === shortcutId
        ? { ...shortcut, currentShortcut: shortcut.defaultShortcut }
        : shortcut
    ));
  };

  // 重置所有快捷键
  const resetAllShortcuts = () => {
    setShortcuts(prev => prev.map(shortcut => ({
      ...shortcut,
      currentShortcut: shortcut.defaultShortcut
    })));
  };

  // 录制快捷键
  const startRecording = () => {
    setIsRecording(true);
    setNewShortcut('');
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!isRecording) return;

    e.preventDefault();
    e.stopPropagation();

    const keys = [];
    if (e.ctrlKey) keys.push('Ctrl');
    if (e.shiftKey) keys.push('Shift');
    if (e.altKey) keys.push('Alt');
    if (e.metaKey) keys.push('Cmd');

    const key = e.key;
    if (key !== 'Control' && key !== 'Shift' && key !== 'Alt' && key !== 'Meta') {
      keys.push(key.length === 1 ? key.toUpperCase() : key);
      setNewShortcut(keys.join('+'));
      setIsRecording(false);
    }
  };

  return (
    <div className="space-y-6" onKeyDown={handleKeyDown} tabIndex={-1}>
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
          快捷键设置
        </h2>
        <p className="text-gray-600 dark:text-gray-400">
          自定义键盘快捷键，提高工作效率
        </p>
      </div>

      {/* 搜索和操作栏 */}
      <div className="flex items-center justify-between space-x-4">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="搜索快捷键..."
            className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
        
        <button
          onClick={resetAllShortcuts}
          className="flex items-center space-x-2 px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
        >
          <RotateCcw className="w-4 h-4" />
          <span>重置所有</span>
        </button>
      </div>

      {/* 冲突检测 */}
      <ShortcutConflictDetector
        shortcuts={shortcuts.reduce((acc, shortcut) => {
          acc[shortcut.id] = shortcut.currentShortcut;
          return acc;
        }, {} as Record<string, string>)}
        onConflictResolved={(actionId, newShortcut) => {
          setShortcuts(prev => prev.map(s =>
            s.id === actionId ? { ...s, currentShortcut: newShortcut } : s
          ));
        }}
      />

      {/* 快捷键列表 */}
      <div className="space-y-6">
        {Object.entries(groupedShortcuts).map(([category, categoryShortcuts]) => (
          <div key={category} className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              {category}
            </h3>
            
            <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
              <div className="divide-y divide-gray-200 dark:divide-gray-700">
                {categoryShortcuts.map((shortcut) => (
                  <ShortcutRow
                    key={shortcut.id}
                    shortcut={shortcut}
                    isEditing={editingShortcut === shortcut.id}
                    newShortcut={newShortcut}
                    isRecording={isRecording}
                    hasConflict={!!conflicts[shortcut.id]}
                    onStartEditing={() => startEditing(shortcut.id)}
                    onCancelEditing={cancelEditing}
                    onSaveShortcut={saveShortcut}
                    onResetShortcut={() => resetShortcut(shortcut.id)}
                    onStartRecording={startRecording}
                    onShortcutChange={setNewShortcut}
                  />
                ))}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// 快捷键行组件
interface ShortcutRowProps {
  shortcut: ShortcutItem;
  isEditing: boolean;
  newShortcut: string;
  isRecording: boolean;
  hasConflict: boolean;
  onStartEditing: () => void;
  onCancelEditing: () => void;
  onSaveShortcut: () => void;
  onResetShortcut: () => void;
  onStartRecording: () => void;
  onShortcutChange: (value: string) => void;
}

const ShortcutRow: React.FC<ShortcutRowProps> = ({
  shortcut,
  isEditing,
  newShortcut,
  isRecording,
  hasConflict,
  onStartEditing,
  onCancelEditing,
  onSaveShortcut,
  onResetShortcut,
  onStartRecording,
  onShortcutChange
}) => {
  const isModified = shortcut.currentShortcut !== shortcut.defaultShortcut;

  return (
    <div className="flex items-center justify-between p-4 group">
      <div className="flex-1 min-w-0 mr-4">
        <div className="flex items-center space-x-2">
          <h4 className="font-medium text-gray-900 dark:text-white">
            {shortcut.name}
          </h4>
          {hasConflict && (
            <AlertTriangle className="w-4 h-4 text-orange-500" />
          )}
          {isModified && (
            <span className="text-xs px-2 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">
              已修改
            </span>
          )}
        </div>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
          {shortcut.description}
        </p>
      </div>

      <div className="flex items-center space-x-2">
        {isEditing ? (
          <>
            <div className="flex items-center space-x-2">
              <input
                type="text"
                value={newShortcut}
                onChange={(e) => onShortcutChange(e.target.value)}
                placeholder={isRecording ? "按下快捷键..." : "输入快捷键"}
                className="w-32 px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                readOnly={isRecording}
              />
              <button
                onClick={onStartRecording}
                className="px-3 py-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded hover:bg-blue-200 dark:hover:bg-blue-800"
              >
                {isRecording ? '录制中...' : '录制'}
              </button>
            </div>
            <button
              onClick={onSaveShortcut}
              className="p-1 text-green-600 hover:text-green-700 dark:text-green-400 dark:hover:text-green-300"
            >
              <Check className="w-4 h-4" />
            </button>
            <button
              onClick={onCancelEditing}
              className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              <X className="w-4 h-4" />
            </button>
          </>
        ) : (
          <>
            <kbd className={`px-2 py-1 text-sm font-mono bg-gray-100 dark:bg-gray-700 rounded ${
              hasConflict ? 'border-2 border-orange-500' : ''
            }`}>
              {shortcut.currentShortcut}
            </kbd>
            <button
              onClick={onStartEditing}
              className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 opacity-0 group-hover:opacity-100 transition-opacity"
            >
              <Edit2 className="w-4 h-4" />
            </button>
            {isModified && (
              <button
                onClick={onResetShortcut}
                className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 opacity-0 group-hover:opacity-100 transition-opacity"
                title="重置为默认值"
              >
                <RotateCcw className="w-4 h-4" />
              </button>
            )}
          </>
        )}
      </div>
    </div>
  );
};
